<?php


namespace app\admin\controller\mall;

use app\admin\model\MallGoods;
use app\admin\model\MallOrder;
use app\admin\model\MallTradeRecordLog;
use app\admin\model\MallUser;
use app\admin\model\MallWithdrawRecord;
use app\admin\model\SystemAdmin;
use app\api\help\SendMsg;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="提现审核列表")
 */
class AuditStatus0 extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallWithdrawRecord();
    }
    
    
    /**
     * @NodeAnotation(title="审核列表")
     */
    public function audit()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['ea_mall_withdraw_record.status', '=', 0];
            $count   = $this->model
                ->withJoin(['user'], 'left')
                ->where($where)
                ->count();
            $list    = $this->model
//                ->withJoin(['user'], 'left')
                ->withJoin(['user'], 'left')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()
                ->toArray();
            $total   = $this->model
//                ->withJoin(['user'], 'left')
                ->withJoin(['user'], 'left')
                ->where($where)
                ->value('SUM(amount)');
            foreach ($list as $key => $value) {
                $list[ $key ][ 'id' ]       = $value[ 'user_id' ];
                $list[ $key ][ 'audit_id' ] = $value[ 'id' ];
            }
            $newArr = ['type' => '', 'user' => ['name' => '总计', 'mobile' => ''], 'amount' => $total];
            array_unshift($list, $newArr);
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="审核详情")
     */
    public function trade_index()
    {
        $userId = MallWithdrawRecord::where('id', input('audit_id'))->value('user_id');
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $userId  = MallWithdrawRecord::where('id', input('id'))->value('user_id');
            $where[] = ['user_id', '=', $userId];
            $where[] = ['trade_type', 'in', [2, 3, 5, 6, 7, 11, 13, 14, 15, 16, 17]];
            $this->assign('id', input('id'));
            $count = MallTradeRecordLog::
            where($where)
                ->count();
            $list  = MallTradeRecordLog::
            where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $reward                 = [
            'allBalance'     => 0,
            'balance'        => 0,
            'failReward'     => 0,
            'successReward'  => 0,
            'withdrawReward' => 0,
            'countBalance'   => 0,
        ];
        $balance                = MallUser::where('id', $userId)->value('balance');                                                                                                                                              //余额
        $reward[ 'balance' ]    = getPrice($balance);                                                                                                                                                                            //余额
        $reward[ 'allBalance' ] = getPrice($balance);                                                                                                                                                                            //余额
        $tradeInfo              = MallTradeRecordLog::where([['user_id', '=', $userId], ['trade_type', 'in', [2, 3, 4, 5, 6, 7, 11, 14, 15, 16, 17]]])->field('SUM(amount) as amount,trade_type')->group('trade_type')->select();//总补贴
        foreach ($tradeInfo as $value) {
            if ($value[ 'trade_type' ] == 2) {//订单支付（余额）
                $reward[ 'allBalance' ]   += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ] -= getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 3) {//拼团失败奖励
                $reward[ 'allBalance' ]   += getPrice($value[ 'amount' ]);
                $reward[ 'failReward' ]   += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ] += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 4) {//成功奖励退回
                $reward[ 'allBalance' ]    -= getPrice($value[ 'amount' ]);
                $reward[ 'successReward' ] -= getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]  -= getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 6) {//余额提现失败
                $reward[ 'allBalance' ]     -= getPrice($value[ 'amount' ]);
                $reward[ 'withdrawReward' ] -= getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]   += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 7) {//拼团成功奖励
                $reward[ 'allBalance' ]    += getPrice($value[ 'amount' ]);
                $reward[ 'successReward' ] += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]  += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 11) {//订单退款（余额
                $reward[ 'allBalance' ]   -= getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ] += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 14) {//微信收款码提现
                $reward[ 'allBalance' ]     += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]   -= getPrice($value[ 'amount' ]);
                $reward[ 'withdrawReward' ] += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 15) {//支付宝收款码提现
                $reward[ 'allBalance' ]     += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]   -= getPrice($value[ 'amount' ]);
                $reward[ 'withdrawReward' ] += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 16) {//支付宝账号提现
                $reward[ 'allBalance' ]     += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]   -= getPrice($value[ 'amount' ]);
                $reward[ 'withdrawReward' ] += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 17) {//推广积分
                $reward[ 'allBalance' ]   += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ] += getPrice($value[ 'amount' ]);
            } elseif ($value[ 'trade_type' ] == 5) {//支付宝账号提现
                $reward[ 'allBalance' ]     += getPrice($value[ 'amount' ]);
                $reward[ 'countBalance' ]   -= getPrice($value[ 'amount' ]);
                $reward[ 'withdrawReward' ] += getPrice($value[ 'amount' ]);
            }
        }
        $this->assign('reward', $reward);
        $this->assign('id', input('audit_id'));
        return $this->fetch();
    }
    
    
    public function approve()
    {
        $this->checkPostRequest();
        $row     = $this->model->whereIn('id', input('id'))->find();
        $adminId = session('admin.id');
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->save(['status' => 1, 'approve_time' => time(), 'approve_admin_id' => $adminId]);
        } catch (\Exception $e) {
            $this->error('审核失败');
        }
        $save ? $this->success('审核成功') : $this->error('审核失败');
    }
    
    
    public function approves()
    {
        $this->checkPostRequest();
        $row     = $this->model->whereIn('id', input('id'))->find();
        $adminId = session('admin.id');
        $row->isEmpty() && $this->error('数据不存在');
        if (empty(input('remark'))) {
            $this->error('驳回理由不能为空');
        }
        if (strlen(input('remark')) > 30) {
            $this->error('最多输入30个字');
        }
        try {
            $save = $row->save(['status' => 10, 'remark' => input('remark'), 'approve_time' => time(), 'approve_admin_id' => $adminId]);
            //将余额退回
            $balance    = Db::table('ea_mall_user')->where('id', $row[ 'user_id' ])->value('balance');
            $amount     = $row[ 'amount' ];
            $surBalance = $balance + $amount;
            Db::table('ea_mall_user')->where('id', $row[ 'user_id' ])->update(['balance' => $surBalance]);
            \app\api\model\MallTradeRecordLog::addRecord($row[ 'user_id' ], $row[ 'id' ], $amount, $surBalance, 6);
            //提现失败短信
            $code = 'SMS_460786198';
            if ( !empty($code)) {
                $mobile = MallUser::where('id', $row[ 'user_id' ])->value('mobile');
                $msg    = ['msg' => input('remark')];
                SendMsg::sendMsg($mobile, $msg, $code);
                
            }
        } catch (\Exception $e) {
            $this->error('审核失败');
        }
        $save ? $this->success('驳回成功') : $this->error('审核失败');
    }
}